package com.noble.meether.logic.login;

import android.text.TextUtils;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.socket.IMProxy;
import com.noble.glamour.module.util.BaseUtil;
import com.noble.glamour.module.util.NotificationsUtils;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.log.PSP;
import com.noble.library.log.PToast;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.third.ThirdConstant;

import java.util.HashMap;

/**
 * 登录逻辑处理
 */
public class LoginMgr implements ModuleBase {

    private final static String LOGINMGR_UID = "MEET_UID";          // 保存当前登录用户账号信息 uid, pw
    private final static String LOGINMGR_COOKIE = "MEET_COOKIE";    // 保存当前登录用户cookie
    private final static String LOGINMGR_AUTH = "MEET_AUTH";        // 保存当前登录用户cookie, 不带auth=

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    /**
     * 获取手机登录验证码
     */
    public void reqSendCode(String mobile, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("mobile", mobile);
        postParams.put("os", 1);
        postParams.put("cid", ModuleMgr.getAppMgr().getChannel());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqSendCode, postParams, complete);
    }

    /**
     * 手机号验证码验证
     */
    public void reqVerifyCode(String mobile, String code, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("type_user", 1);     // 用户类型 1：手机 2：微信 3：QQ
        postParams.put("mobile", mobile);
        postParams.put("code", code);
        reqLogin(postParams, complete);
    }

    /**
     * 微信三方登录
     */
    public void weChatLogin(String openId, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("type_user", 2);
        postParams.put("auth_wx", openId);
        reqLogin(postParams, complete);
    }

    /**
     * QQ三方登录
     */
    public void qqLogin(String openId, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("type_user", 3);
        postParams.put("auth_qq", openId);
        reqLogin(postParams, complete);
    }

    private void reqLogin(HashMap<String, Object> postParams, final RequestComplete complete) {
        postParams.put("cid", ModuleMgr.getAppMgr().getChannel());       // 渠道号
        postParams.put("os", 1);        // 1: android 2: ios
        postParams.put("app_id", Constant.getAppId());
        postParams.put("ver", ModuleMgr.getAppMgr().getVerCode());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqLogin, postParams, response -> {
            LoadingDialog.closeLoadingDialog(500);
            if (!response.isOk()) return;

            LoginResult data = (LoginResult) response.getBaseData();
            setCookie(data.getAuth());
            putAllLoginInfo(data.getUid(), true);
            MsgMgr.getInstance().sendMsg(MsgType.MT_App_Login, App.isLogin);

            final HttpResponse tmpResponse = response;

            // 去请求个人资料
            ModuleMgr.getCenterMgr().reqMyInfo(response1 -> {
                if (response1.isOk()) {
                    UserDetail userDetail = (UserDetail) response1.getBaseData();

                    if (userDetail.noGender() && complete != null) { // 资料未完善
                        complete.onRequestComplete(tmpResponse);
                        return;
                    }
                    UIShow.showMainClearTask(App.activity);
                    return;
                }
                PToast.showShort("获取资料失败，请重试");
            }, "LoginMgr.reqLogin()");
        });
    }

    /**
     * 微信获取AccessToken
     */
    public void loadAccessToken(String code, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("appid", ThirdConstant.WEIXIN_APP_ID);
        getParams.put("secret", ThirdConstant.WEIXIN_APP_SECRET);
        getParams.put("code", code);
        getParams.put("grant_type", "authorization_code");
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXAccessToken, getParams, complete);
    }

    /**
     * 微信获取用户资料
     */
    public void loadUserInfo(String openid, String accessToken, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("access_token", accessToken);
        getParams.put("openid", openid);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXUserInfo, getParams, complete);
    }

    /**
     * 保存登录信息
     */
    private void putAllLoginInfo(long uid, boolean isUserLogin) {
        setUid(uid + "");
        setLoginInfo(uid, isUserLogin);  //设置登录状态
    }

    /**
     * 保存单独的 uid
     */
    public void setUid(String uid) {
        PSP.getInstance().put(LOGINMGR_UID, uid);
    }

    public long getUid() {
        String uid = PSP.getInstance().getString(LOGINMGR_UID, "");
        if (!TextUtils.isEmpty(uid)) {
            return BaseUtil.getLong(uid, 0);
        }
        return 0L;
    }

    /**
     * 初始化登陆信息
     */
    public void initCookie() {
        long uid = getUid();
        if (uid == 0) {
            clearCookie();
            return;
        }
        setLoginInfo(uid, true);
    }

    /**
     * 保存cookie
     */
    private void setCookie(String cookie) {
        PSP.getInstance().put(LOGINMGR_COOKIE, "auth=" + cookie);
        PSP.getInstance().put(LOGINMGR_AUTH, cookie);
    }

    /**
     * 判断Cookie是否存在
     */
    public boolean checkAuthIsExist() {
        return !TextUtils.isEmpty(getAuth());
    }

    /**
     * 获取cookie
     */
    public String getCookie() {
        return PSP.getInstance().getString(LOGINMGR_COOKIE, "");
    }

    /**
     * 获取无 auth= 的cookie
     */
    public String getAuth() {
        return PSP.getInstance().getString(LOGINMGR_AUTH, "");
    }

    /**
     * 获取cookie + ver
     */
    public String getCookieVerCode() {
        String cookie = getCookie();
        if (!TextUtils.isEmpty(cookie)) {
            return cookie + ";" + "v=" + ModuleMgr.getAppMgr().getVerCode();
        } else {
            clearCookie();
            return "v=" + ModuleMgr.getAppMgr().getVerCode();
        }
    }

    /**
     * 清空本地Cookie
     */
    public void clearCookie() {
        setCookie("");
    }

    /**
     * 设置登录信息，并发送登录信息。
     *
     * @param isUserLogin 　进行登录请求或处于登录状态
     */
    private void setLoginInfo(long uid, boolean isUserLogin) {
        changeIsLogin(isUserLogin && (TextUtils.isEmpty(getAuth()) || uid == 0) ? 0 : uid);
    }

    private void changeIsLogin(long uid) {
        App.uid = uid;
        App.isLogin = uid != 0;
    }

    /**
     * 退出登录，并清空用户登录信息
     */
    public void logout() {
        IMProxy.getInstance().logout();//退出登录的时候退出socket
        NotificationsUtils.cancelAll();//如果还有通知栏提示，在退出帐号的时候全部清掉
        setUid("");//清空uid
        clearCookie();//在setLoginInfo方法之前执行
        setLoginInfo(0, false);
    }
}
